package com.zp.self.module.令牌桶.config;

import com.zp.self.entity.MessageEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author By ZengPeng
 * @Description
 * @date in  2021/3/26 11:12
 * @Modified By
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(RocketMQProperties.class)
public class ConsumerConfig {
    @Resource
    private RocketMQProperties rocketMQProperties;
    /**
     * 监听到中间件，发布到listener
     */
    @Resource
    private ApplicationEventPublisher publisher ;

    /**
     * 初始化消费者
     */
    @Bean
    public void initConsumerInstance() {
        List<Map<String, Object>> consumerList = rocketMQProperties.getConsumerList();
        if (consumerList.size() > 0) {
            consumerList.stream().forEach(map -> {
                try {
                    pushConsumer(map);
                } catch (MQClientException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * 创建消息消费的实例
     * @throws MQClientException 客户端异常
     */
    private DefaultMQPushConsumer pushConsumer(Map consumerConfig) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerConfig.get("groupName").toString());
        consumer.setNamesrvAddr(consumerConfig.get("namesrvAddr").toString());

        //判断是否是广播模式
        if (Boolean.parseBoolean(consumerConfig.get("consumerBroadCasting").toString())) {
            consumer.setMessageModel(MessageModel.BROADCASTING);
        }
        //设置批量消费
        consumer.setConsumeMessageBatchMaxSize(Integer.parseInt(consumerConfig.get("consumerBatchMaxSize").toString()) == 0 ? 1 : Integer.parseInt(consumerConfig.get("consumerBatchMaxSize").toString()));

        //获取topic和tag
        consumer.subscribe(consumerConfig.get("topic").toString(), "*");


        if (Boolean.parseBoolean(consumerConfig.get("enableOrderConsumer").toString())) {
            // 顺序消费
            consumer.registerMessageListener(new MessageListenerOrderly() {
                @Override
                public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                    try {
                        context.setAutoCommit(true);
                        if (msgs.size() == 0)
                            return ConsumeOrderlyStatus.SUCCESS;
                        publisher.publishEvent(new MessageEvent(msgs, consumer));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                    }
                    return ConsumeOrderlyStatus.SUCCESS;
                }
            });
        } else {
            //并发消费
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(
                        List<MessageExt> msgs,
                        ConsumeConcurrentlyContext context) {
                    try {
                        if (msgs.size() == 0)
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        publisher.publishEvent(new MessageEvent(msgs, consumer));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
        }
        //从上次消费节点开始
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.start();
        return consumer;
    }



    /**
     * 消息过滤
     *
     * @param msgs
     * @return
     */
    private List<MessageExt> filterMessage(List<MessageExt> msgs) {
        long startTime = System.currentTimeMillis();
        if (rocketMQProperties.isEnableHistoryConsumer()) {
            msgs = msgs.stream()
                    .filter(item -> startTime - item.getBornTimestamp() < 0)
                    .collect(Collectors.toList());
        }
        return msgs;
    }

}
